<template>
  <div class="order-list">
    <!-- 搜索和操作区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="订单号">
          <el-input
            v-model="searchForm.orderNo"
            placeholder="请输入订单号"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
            @clear="handleSearch"
          />
        </el-form-item>
        <el-form-item label="客户名称">
          <el-input
            v-model="searchForm.customerName"
            placeholder="请输入客户名称"
            clearable
            style="width: 150px"
            @keyup.enter="handleSearch"
            @clear="handleSearch"
          />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择订单状态"
            clearable
            style="width: 150px"
            @change="handleSearch"
            @clear="handleSearch"
          >
            <el-option label="待确认" value="pending" />
            <el-option label="已确认" value="confirmed" />
            <el-option label="生产中" value="production" />
            <el-option label="已发货" value="delivered" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="支付状态">
          <el-select
            v-model="searchForm.paymentStatus"
            placeholder="请选择支付状态"
            clearable
            style="width: 150px"
            @change="handleSearch"
            @clear="handleSearch"
          >
            <el-option label="未支付" value="unpaid" />
            <el-option label="部分支付" value="partial" />
            <el-option label="已支付" value="paid" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
            @change="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch"> 搜索 </el-button>
          <el-button :icon="Refresh" @click="handleReset"> 重置 </el-button>
        </el-form-item>
      </el-form>

      <div class="action-buttons">
        <el-button type="primary" :icon="Plus" @click="handleAdd"> 新增订单 </el-button>
        <el-button
          type="danger"
          :icon="Delete"
          :disabled="!selectedRows.length"
          @click="handleBatchDelete"
        >
          批量删除
        </el-button>
        <el-button :icon="Download" @click="handleExport"> 导出数据 </el-button>
      </div>
    </el-card>

    <!-- 订单列表表格 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="orderList"
        stripe
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="orderNo" label="订单号" width="140" fixed="left" />
        <el-table-column prop="customerName" label="客户名称" width="100" />
        <el-table-column label="产品信息" width="180">
          <template #default="{ row }">
            <div class="product-info">
              <div
                v-for="(product, index) in row.products.slice(0, 2)"
                :key="index"
                class="product-item"
              >
                {{ product.productName }} × {{ product.quantity }}{{ product.unit }}
              </div>
              <div v-if="row.products.length > 2" class="more-products">
                +{{ row.products.length - 2 }}个产品
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="订单金额" width="100">
          <template #default="{ row }"> {{ formatAmount(row.totalAmount) }} </template>
        </el-table-column>
        <el-table-column prop="finalAmount" label="实付金额" width="100">
          <template #default="{ row }">
            <span class="final-amount">{{ formatAmount(row.finalAmount) }}</span>
            <div v-if="row.discountAmount > 0" class="discount-info">
              优惠: {{ formatAmount(row.discountAmount) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="订单状态" width="90">
          <template #default="{ row }">
            <el-tag :type="getOrderStatusType(row.status)" size="small">
              {{ getOrderStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="paymentStatus" label="支付状态" width="90">
          <template #default="{ row }">
            <el-tag :type="getPaymentStatusType(row.paymentStatus)" size="small">
              {{ getPaymentStatusTag(row.paymentStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="deliveryDate" label="交货日期" width="100">
          <template #default="{ row }">
            {{ formatDate(row.deliveryDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="140">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)"> 查看 </el-button>
            <el-button
              v-if="row.status === 'pending'"
              type="success"
              size="small"
              @click="handleConfirm(row)"
            >
              确认
            </el-button>
            <el-button
              v-if="['pending', 'confirmed'].includes(row.status)"
              type="warning"
              size="small"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              v-if="row.status !== 'cancelled'"
              type="danger"
              size="small"
              @click="handleCancel(row)"
            >
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 订单详情对话框 -->
    <OrderDetailDialog v-model="detailVisible" :order="currentOrder" />

    <!-- 新增/编辑订单对话框 -->
    <OrderFormDialog
      v-model="formVisible"
      :is-edit="isEdit"
      :order-data="isEdit ? orderForm : null"
      :customer-options="customerOptions"
      :submit-loading="submitLoading"
      @submit="handleFormSubmit"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import { Search, Refresh, Plus, Delete, Download } from '@element-plus/icons-vue'
import {
  getOrderList,
  getOrderDetail,
  createOrder,
  updateOrder,
  deleteOrder,
  updateOrderStatus,
} from '@/api/order'
import { getCustomerList } from '@/api/customer'
import {
  formatAmount,
  formatDate,
  formatDateTime,
  getOrderStatusLabel,
  getPaymentStatusTag,
} from '@/utils'
import type { Order, Customer } from '@/types'
import OrderDetailDialog from './components/OrderDetailDialog.vue'
import OrderFormDialog from './components/OrderFormDialog.vue'
import { useRoute } from 'vue-router'

// 路由对象
const route = useRoute()

// 搜索表单
const searchForm = reactive({
  orderNo: '',
  customerName: '',
  status: '',
  paymentStatus: '',
})

// 日期范围
const dateRange = ref<[string, string] | null>(null)

// 订单列表数据
const orderList = ref<Order[]>([])
const loading = ref(false)
const selectedRows = ref<Order[]>([])

// 分页数据
const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0,
})

// 订单详情
const detailVisible = ref(false)
const currentOrder = ref<Order | null>(null)

// 表单相关
const formVisible = ref(false)
const isEdit = ref(false)
const submitLoading = ref(false)
const orderForm = ref<Order | null>(null)

// 客户选项
const customerOptions = ref<Customer[]>([])

// 获取订单状态类型
const getOrderStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: 'warning',
    confirmed: 'primary',
    production: 'info',
    delivered: 'success',
    cancelled: 'danger',
  }
  return statusMap[status] || 'info'
}

// 获取支付状态类型
const getPaymentStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    unpaid: 'danger',
    partial: 'warning',
    paid: 'success',
  }
  return statusMap[status] || 'info'
}

// 加载客户选项
const loadCustomerOptions = async () => {
  try {
    const { data } = await getCustomerList({ page: 1, pageSize: 1000 })
    if (data?.list) {
      customerOptions.value = data.list
    }
  } catch (error) {
    console.error('加载客户列表失败:', error)
  }
}

// 加载订单列表
const loadOrderList = async () => {
  loading.value = true
  try {
    // 构建搜索参数，将表单字段映射为API期望的格式
    const searchParams: any = {
      page: pagination.page,
      pageSize: pagination.pageSize,
    }

    // 处理关键字搜索：订单号或客户名称
    if (searchForm.orderNo || searchForm.customerName) {
      searchParams.keyword = searchForm.orderNo || searchForm.customerName
    }

    // 处理其他搜索条件
    if (searchForm.status) {
      searchParams.status = searchForm.status
    }
    if (searchForm.paymentStatus) {
      searchParams.paymentStatus = searchForm.paymentStatus
    }

    // 处理日期范围
    if (dateRange.value) {
      searchParams.dateRange = dateRange.value
    }

    const { data } = await getOrderList(searchParams)
    if (data) {
      // 使用修复后的API返回格式
      orderList.value = data.list || []
      pagination.total = data.total || 0
    }
  } catch (error) {
    ElMessage.error('加载订单列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  loadOrderList()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    orderNo: '',
    customerName: '',
    status: '',
    paymentStatus: '',
  })
  dateRange.value = null
  pagination.page = 1
  loadOrderList()
}

// 新增订单
const handleAdd = () => {
  isEdit.value = false
  orderForm.value = null
  formVisible.value = true
}

// 查看订单详情
const handleView = async (row: Order) => {
  try {
    const { data } = await getOrderDetail(row.id)
    currentOrder.value = data
    detailVisible.value = true
  } catch (error) {
    ElMessage.error('获取订单详情失败')
  }
}

// 确认订单
const handleConfirm = async (row: Order) => {
  try {
    await updateOrderStatus(row.id, 'confirmed')
    ElMessage.success('订单确认成功')
    loadOrderList()
  } catch (error) {
    ElMessage.error('订单确认失败')
  }
}

// 编辑订单
const handleEdit = async (row: Order) => {
  try {
    const { data } = await getOrderDetail(row.id)
    isEdit.value = true
    orderForm.value = data
    formVisible.value = true
  } catch (error) {
    ElMessage.error('获取订单信息失败')
  }
}

// 取消订单
const handleCancel = async (row: Order) => {
  try {
    await ElMessageBox.confirm(`确定要取消订单 "${row.orderNo}" 吗？`, '取消确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    await updateOrderStatus(row.id, 'cancelled')
    ElMessage.success('订单取消成功')
    loadOrderList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('订单取消失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 个订单吗？`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )

    for (const order of selectedRows.value) {
      await deleteOrder(order.id)
    }
    ElMessage.success('批量删除成功')
    loadOrderList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  }
}

// 导出数据
const handleExport = async () => {
  try {
    // 获取所有订单数据用于导出
    const response = await getOrderList({
      page: 1,
      pageSize: 10000, // 获取大量数据
      ...searchForm,
      ...(dateRange.value && { dateRange: dateRange.value }),
    })
    // JSON Server直接返回数组数据，经过拦截器包装后在data中
    const orders = Array.isArray(response.data) ? response.data : []

    // 动态导入xlsx库
    const XLSX = await import('xlsx')

    // 准备导出数据
    const exportData = orders.map((order) => ({
      订单号: order.orderNo,
      客户名称: order.customerName,
      订单状态: getOrderStatusLabel(order.status),
      支付状态: getPaymentStatusTag(order.paymentStatus),
      订单金额: order.totalAmount,
      折扣金额: order.discountAmount || 0,
      实付金额: order.finalAmount,
      交货日期: order.deliveryDate,
      创建时间: formatDate(order.createTime),
      更新时间: formatDate(order.updateTime),
      备注: order.remark || '',
    }))

    // 创建工作簿
    const wb = XLSX.utils.book_new()
    const ws = XLSX.utils.json_to_sheet(exportData)

    // 设置列宽
    const colWidths = [
      { wch: 15 }, // 订单号
      { wch: 15 }, // 客户名称
      { wch: 10 }, // 订单状态
      { wch: 12 }, // 支付状态
      { wch: 12 }, // 订单金额
      { wch: 12 }, // 折扣金额
      { wch: 12 }, // 实付金额
      { wch: 12 }, // 交货日期
      { wch: 20 }, // 创建时间
      { wch: 20 }, // 更新时间
      { wch: 20 }, // 备注
    ]
    ws['!cols'] = colWidths

    // 添加工作表
    XLSX.utils.book_append_sheet(wb, ws, '订单数据')

    // 生成文件名
    const fileName = `订单数据导出_${new Date().toISOString().slice(0, 10)}.xlsx`

    // 导出文件
    XLSX.writeFile(wb, fileName)

    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 表格选择变化
const handleSelectionChange = (selection: Order[]) => {
  selectedRows.value = selection
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.page = 1
  loadOrderList()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.page = page
  loadOrderList()
}

// 表单提交处理
const handleFormSubmit = async (formData: any) => {
  try {
    submitLoading.value = true

    if (isEdit.value) {
      await updateOrder(formData.id, formData)
      ElMessage.success('订单更新成功')
    } else {
      await createOrder(formData)
      ElMessage.success('订单创建成功')
    }

    formVisible.value = false
    loadOrderList()
  } catch (error) {
    ElMessage.error(isEdit.value ? '订单更新失败' : '订单创建失败')
  } finally {
    submitLoading.value = false
  }
}

// 根据路由参数初始化订单列表筛选
const initFromRouteQuery = () => {
  const q = route.query || {}
  Object.assign(searchForm, {
    orderNo: typeof q.orderNo === 'string' ? q.orderNo : '',
    customerName: typeof q.customerName === 'string' ? q.customerName : '',
    status: typeof q.status === 'string' ? q.status : '',
    paymentStatus: typeof q.paymentStatus === 'string' ? q.paymentStatus : '',
  })
  if (typeof q.title === 'string' && q.title) {
    document.title = `${q.title} - 布匹销售系统`
  }
}

onMounted(() => {
  initFromRouteQuery()
  loadOrderList()
  loadCustomerOptions()
})

// 监听路由变化以刷新列表
watch(
  () => route.fullPath,
  () => {
    initFromRouteQuery()
    pagination.page = 1
    loadOrderList()
  },
)
</script>

<style scoped>
.order-list {
  padding: 0;
}

.search-card {
  margin-bottom: 16px;
}

.search-form {
  margin-bottom: 16px;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.table-card {
  min-height: 600px;
}

.product-info {
  font-size: 12px;
}

.product-item {
  margin-bottom: 4px;
}

.more-products {
  color: #909399;
  font-style: italic;
}

.final-amount {
  font-weight: 600;
  color: #f56c6c;
}

.discount-info {
  font-size: 12px;
  color: #67c23a;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-form .el-form-item {
    margin-bottom: 16px;
  }

  .action-buttons {
    flex-wrap: wrap;
  }

  .el-table {
    font-size: 12px;
  }
}
</style>
